/**
 * Created by hylin on  2014/7/16.
 * 回放页面
 */
var playbackPage = function(){
    var map = null,
        list = [],
        nextList = [],
        marker = null,
        polyline = null,
        playing = false,
        pause = false,
        speed = 600,
        currentIndex = 0,
        playTimer = null,
        lastData = null,
        beginTime = null,
        endTime = null,
        threshold = 1000,
        timeThreshold = 30*24*60*60*1000,
        firstLoad = true,
        mileage = 0,
        params = goome.wx.utils.defaultParams(),
        headerHeight = $('.header').height(),
        $infobar = $('.info-bar'),
        $playBtn = $('#play-btn'),
        $progressBar = $('#progress-bar'),
        $block = $progressBar.find('.block'),
        $line = $progressBar.find('.line'),
        $realtime = $('#real-time'),
        $passLine = $progressBar.find('.pass-line'),
        $timeSelectorBtn = $('#time-selector-btn'),
        $timeSelector = $('#time-selector'),
        $customTimeMask = $('#custom-time-mask'),
        $beginTime = $('#begin-time'),
        $endTime = $('#end-time'),
        $mapContainer = $('#map-container');

    params.limit = threshold;
    params.imei = goome.wx.utils.params().imei;
    function loadData(bTime, eTime, goPlay){
        params.begin_time = bTime;
        params.end_time = eTime;
        console.log(params)
        $.when(getRemoteData('devices/history'))
            .done(function(results){
                if(results && results.errcode === 0){
                    if(list.length == 0){
                        list = results.data;
                    }else{
                        nextList = results.data;
                    }
                    if(goPlay) play();
                    if(firstLoad){
                        firstLoad = false;
                        if(list.length > 0) {
                            loadData(list[list.length - 1].gps_time, eTime);
                        }
                    }
                }else{
                    goome.wx.utils.showTip("出错了");
                }
            });
    }
    function getRemoteData(url){
        return $.ajax({
            url: goome.wx.config.apiUrl+url,
            data: params,
            dataType: 'jsonp',
            success: function(results){
                console.log(results)
                return results
            },
            error: function(err){
                goome.wx.utils.showTip(err);
            }
        });
    }

    function resize(){
        $mapContainer.height($(window).height() - headerHeight);
    }

    function showDatePicker(){
        $customTimeMask.show();
    }
    function play(){
        if(!marker){
            marker = new BMap.Marker(map.getCenter(), {
                icon: new BMap.Icon('images/icon_playback_marker.png', new BMap.Size(15,15))
            });
            map.addOverlay(marker);
        }
        if(list.length == 0){
            finished();
            return;
        }
        playing = true;
        $playBtn.addClass('pause');
        playTimer = setInterval(function(){
            if(pause){
                playing = false;
                $playBtn.removeClass('pause');
                clearInterval(playTimer);
            }else {
                run();
            }
        }, speed);
    }

    function run(){
        var data = list[currentIndex++],
            path = polyline.getPath(),
            point = new BMap.Point(data.lng, data.lat);
        if(data) {
            if(currentIndex == 1){
                map.centerAndZoom(point, 16);
            }
            marker.setPosition(point);
            path.push(point);
            polyline.setPath(path);
            if(lastData) {
                mileage = goome.wx.utils.distance(lastData.lat, lastData.lng, data.lat, data.lng, mileage);
            }
            lastData = data;
            var ratio = (data.gps_time - beginTime) / (endTime - beginTime) * 100;
            $block.css('left', ratio + '%');
            $passLine.width(ratio+'%');
            $realtime.text(goome.wx.utils.dateFormat(new Date(data.gps_time*1000), '%h:%m'));
            $infobar.find('.left').text(goome.wx.utils.dateFormat(data.gps_time));
            $infobar.find('.middle').text(data.speed+' km/h');
            $infobar.find('.right').text(wxLang.direction+': '+goome.wx.utils.getDirection(data.course));
            if (currentIndex >= list.length - 1) {
                if(nextList.length > 0 && (list.length == threshold)) {
                    list = nextList;
                    nextList = [];
                    currentIndex = 0;
                    loadData(list[list.length - 1].gps_time, endTime);
                }else{
                    finished();
                }
            }
            if(!map.getBounds().containsPoint(point)){
                map.setCenter(point);
            }
        }else{
            finished();
        }
    }
    function finished(){
        playing = false;
        pause = false;
        list = [];
        nextList = [];
        clearInterval(playTimer);
        $playBtn.removeClass('pause');
        goome.wx.utils.showTip(wxLang.totalMileage+ ': '+mileage.toFixed(2)+' '+wxLang.km);
    }
    function continuePlay(){
        pause = false;
        playing = true;
        playTimer = setInterval(function(){
            if(pause){
                playing = false;
                clearInterval(playTimer);
            }else {
                run();
            }
        }, speed);
    }
    function initMap(){
        var center = new BMap.Point(113.920787,22.573978);
        map = new BMap.Map('map-container');
        map.centerAndZoom(center, 5);
        map.addControl(new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_ZOOM,
            offset: new BMap.Size(0, 80)
        }));
        map.addControl(new BMap.ScaleControl({
            anchor: BMAP_ANCHOR_TOP_LEFT,
            offset: new BMap.Size(0, 80)
        }));
        map.enableScrollWheelZoom(true);

        polyline = new BMap.Polyline([], {strokeColor:"#00FF00", strokeWeight:4, strokeOpacity:0.8});
        map.addOverlay(polyline);
    }

    function initHtml(){

    }
    function reset(){
        list = [];
        nextList = [];
        playing = false;
        pause = false;
        currentIndex = 0;
        lastData = null;
        firstLoad = true;
        clearInterval(playTimer);
        polyline.setPath([]);
    }
    function bindEvents(){
        $playBtn.on('click', function(e){
            if(!playing && !pause){
                $timeSelectorBtn.click();
            }else{
                if(pause) {
                    $playBtn.addClass('pause');
                    continuePlay();
                }else{
                    $playBtn.removeClass('pause');
                    pause = true;
                }
            }
        });
        $timeSelectorBtn.on('click', function(){
            var $this = $(this);
            if($this.data('open')){
                $timeSelector.hide();
                $this.data('open', false);
            }else{
                $timeSelector.show();
                $this.data('open', true);
            }
        });
        $timeSelector.on('click','li', function(e){
            var $this = $(this),
                val = ''+$this.data('type');
            reset();
            beginTime = new Date();
            endTime = Math.floor(new Date().getTime()/1000);
            beginTime = Math.floor(new Date(beginTime.getFullYear()+'/'+(beginTime.getMonth()+1)+'/'+beginTime.getDate()).getTime()/1000);
            switch (val){
                case '1':
                    loadData(beginTime, endTime, true);
                    break;
                case '2':
                    endTime = beginTime;
                    beginTime = beginTime-24*60*60;
                    loadData(beginTime, endTime, true);
                    break;
                case '3':
                    endTime = beginTime;
                    beginTime = beginTime-2*24*60*60;
                    loadData(beginTime, endTime, true);
                    break;
                case '4':
                    beginTime = endTime - 60*60;
                    loadData(beginTime, endTime, true);
                    break;
                default :
                    showDatePicker();
                    break;
            }
            $timeSelectorBtn.click();
        });
        $progressBar.on('click', function(e){
            if(!beginTime || !endTime){
                $timeSelectorBtn.click();
                return;
            }
            var left = e.clientX - $progressBar.offset().left,
                w = $progressBar.width();
            left < 0 && (left = 0);
            left > w && (left = w);
            var time = Math.floor((endTime - beginTime)*(left/w)) + beginTime;
            $block.css('left', left);
            $passLine.width(left);
            reset();
            loadData(time, endTime, true);
        });
        $customTimeMask.on('click', 'input', function(){
            var $this = $(this),
                action = $this.data('action');
            if(action == 'cancel'){
                $customTimeMask.hide();
            }else if(action == 'confirm'){
                var beginTime = $beginTime.val(),
                    endTime = $endTime.val();
                if(!beginTime || !endTime){
                    goome.wx.utils.showTip(wxLang.selectTime);
                    return false;
                }
                beginTime = new Date(beginTime).getTime()/1000;
                endTime = new Date(endTime).getTime()/1000;
                if(endTime < beginTime){
                    goome.wx.utils.showTip(wxLang.selectTimeTip1);
                    return false;
                }
                if(endTime - beginTime > timeThreshold/1000){
                    goome.wx.utils.showTip(wxLang.selectTimeTip2);
                    return false;
                }
                loadData(beginTime, endTime, true);
                $customTimeMask.hide();
            }else{
                $(this).mobiscroll('show');
            }
        });
    }
    function initDatepicker(){
        //初始化日期控件
        var opt = {
            theme: 'mobiscroll',
            display: 'bottom',
            mode: 'scroller',
            maxDate: new Date(),
            minDate: new Date(new Date().getTime()-timeThreshold),
            defaultValue: new Date(),
            animate: 'none'
        };
        if(goome.wx.utils.params().lang.indexOf('zh')>-1){
            opt.lang = 'zh';
        }
        $.mobiscroll.setDefaults({
            minWidth: 40
        });
        $beginTime.mobiscroll().datetime(opt);
        $endTime.mobiscroll().datetime(opt);
    }
    function init(){
        initDatepicker();
        bindEvents();
        resize();
        initMap();
        $timeSelectorBtn.click();
    }
    return {
        init: init
    };
}();